package cn.example.practice.util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class VerifyCodeGenerator {
    private static final int WIDTH = 100;
    private static final int HEIGHT = 30;
    private static final int LENGTH = 4;
    private static final int LINE_COUNT = 20;
    private static final String CHAR_SET = "0123456789" +
            "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
            "abcdefghijklmnopqrstuvwxyz";
    private static final Random random = new Random();

    private final BufferedImage image;
    private final String code;

    public VerifyCodeGenerator() {
        image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_3BYTE_BGR);
        Graphics g = image.getGraphics();

        // 设置背景
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, WIDTH, HEIGHT);

        // 生成验证码
        code = drawChar(g);

        // 添加干扰线
        for (int i = 0; i < LINE_COUNT; i++) {
            drawLine(g);
        }

        g.dispose();
    }

    private Color getRandomColor() {
        return new Color(random.nextInt(255),
                random.nextInt(255),
                random.nextInt(255));
    }

    private Font getFont() {
        return new Font("Fixedsys", Font.BOLD, 20);
    }

    private String drawChar(Graphics g) {
        StringBuilder codeBuilder = new StringBuilder();
        g.setFont(getFont());

        for (int i = 0; i < LENGTH; i++) {
            char c = CHAR_SET.charAt(random.nextInt(CHAR_SET.length()));
            g.setColor(getRandomColor());
            g.drawString(String.valueOf(c), 20 * i + 10, 20);
            codeBuilder.append(c);
        }

        return codeBuilder.toString();
    }

    private void drawLine(Graphics g) {
        int x = random.nextInt(WIDTH);
        int y = random.nextInt(HEIGHT);
        int xl = random.nextInt(13);
        int yl = random.nextInt(15);
        g.setColor(getRandomColor());
        g.drawLine(x, y, x + xl, y + yl);
    }

    public BufferedImage getImage() {
        return image;
    }

    public String getCode() {
        return code;
    }
}
